/**
 * GenerateParentheses.java created by zhangzhidong 
 * at 下午5:04:15 2017年9月7日
 */
package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangzhidong<br>
 * comment generated at 2017年9月7日下午5:04:15<br>
 * 
 */
public class GenerateParentheses {
	public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, "", 0, 0, n);
        return list;
    }
    
    public void backtrack(List<String> list, String str, int open, int close, int max){
        
        if(str.length() == max*2){
            list.add(str);
            return;
        }
        
        if(open < max)
            backtrack(list, str+"(", open+1, close, max);
        if(close < open)
            backtrack(list, str+")", open, close+1, max);
    }
    public static void main(String[] args) {
		GenerateParentheses gp = new GenerateParentheses();
		gp.generateParenthesis(3);
	}
}
